package com.learn.demo.netty.rpc.netty;

import com.learn.demo.netty.rpc.provider.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端业务处理器
 *
 * @author banjiawei
 * @date 2022/03/11
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取客户端消息，并调用服务
        log.info("msg：{}", msg);
        //客户端调用服务器API时，我们需要定义一个协议，如msg需以XXX打头，我们才对应调用对应的业务处理
        if(msg.toString().startsWith("HelloServer#sayHello#")){
            String hello = new HelloServiceImpl().sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
            ctx.writeAndFlush(hello);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
